package com.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@Slf4j
//@Configuration
public class CustomEventListener {

    private final BlockingQueue<BrokerAvailabilityEvent> eventQueue = new LinkedBlockingQueue<>();

    @EventListener(classes = ApplicationEvent.class)
    public void publishEvent(ApplicationEvent event) {
        publishEvent((Object) event);
    }

    public void publishEvent(Object event) {
        log.debug("Processing ApplicationEvent " + event);
        if (event instanceof BrokerAvailabilityEvent) {
            this.eventQueue.add((BrokerAvailabilityEvent) event);
        }
    }

//    public void expectBrokerAvailabilityEvent(boolean isBrokerAvailable) throws InterruptedException {
//        BrokerAvailabilityEvent event = this.eventQueue.poll(20000, TimeUnit.MILLISECONDS);
//        Assert.notNull(event, "Times out waiting for BrokerAvailabilityEvent[" + isBrokerAvailable + "]");
//        Assert.isTrue(event.isBrokerAvailable() == isBrokerAvailable, "Times out waiting for BrokerAvailabilityEvent[" + isBrokerAvailable + "]");
//    }
}